package Core;

import Core.IConnectionListener;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import javax.microedition.io.SocketConnection;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author Mr Bao
 */
public class ConnectionHandler {

    protected PrintStream out;
    protected DataInputStream in;
    protected SocketConnection socket;
    protected IConnectionListener connectionListener;
    protected ReaderThread readerThread;
    protected WriterThread writerThread;

    public ConnectionHandler(SocketConnection socket) throws IOException {
        this.socket = socket;

        out = new PrintStream(this.socket.openOutputStream());
        in = new DataInputStream(this.socket.openInputStream());

        readerThread = new ReaderThread(in, this);
        writerThread = new WriterThread(out);
        writerThread.start();
    }

    public void SetListener(IConnectionListener listener) {
        this.connectionListener = listener;
        readerThread.SetListener(listener);
        readerThread.start();
    }

    public void Shutdown(boolean notify) {
        readerThread.Halt();
        writerThread.Halt();
        writerThread.FlushOutputQueue();
        try {
            socket.close();
        } catch (Exception e) {
        }
        if (notify) {
            connectionListener.SocketClosed();
        }
    }

    public void QueueMessage(String message) {
        writerThread.QueueMessage(message);
    }
}
